package com.zuohuaipan.headine.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zuohuaipan.headine.R;
import com.zuohuaipan.headine.adapter.Video_Adapter;
import com.zuohuaipan.headine.bean.Video_Bean;
import com.zuohuaipan.lazyviewpager_master.LazyFragmentPagerAdapter;
import com.zuohuaipan.xlistview.XListView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NwsVideoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NwsVideoFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable, XListView.IXListViewListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private XListView xlv;
    ArrayList<Video_Bean> arrayList;
    private Video_Adapter video_adapter;
    private Callback.Cancelable cancelable;
    int index = 0;
    private boolean injected = false;

    public NwsVideoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NwsVideoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NwsVideoFragment newInstance(String param1, String param2) {
        NwsVideoFragment fragment = new NwsVideoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_nws_video, container, false);
        //初始化
        initView(view);
        arrayList = new ArrayList<>();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //判断有没有初始化
        if (!injected) {//没有初始化回调getview方法
            x.view().inject(this, getView());
        }

        onRefresh();



        //监听
        setxlvListener();
    }

    public void setxlvListener() {
        xlv.setPullRefreshEnable(true);
        xlv.setPullLoadEnable(true);
        xlv.setXListViewListener(this);

        // listview在滑动状态时，不加载图片
//        xlv.setOnScrollListener(new );

    }

    /**
     * 初始化url
     *
     * @param type
     * @param typeid
     * @param index
     */

    private RequestParams geturl(String type, String typeid, int index) {
        String url = String.format("http://c.3g.163.com/nc/video/%1$s/%2$s/n/%3$s-10.html", type, typeid, index);

        return new RequestParams(url);
    }

    public void getvideo(String type, final String typeid, int index) {
        RequestParams params = geturl(type, typeid, index);
        cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("zzz", "00000000000000" + result);
                //解析数据
                arrayList.addAll(toStr(result, typeid));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                UpdateUI(arrayList);
            }
        });

    }

    private void UpdateUI(ArrayList<Video_Bean> arrayList) {
        if (index == 0) {
            video_adapter = new Video_Adapter(getActivity(), arrayList);
            xlv.setAdapter(video_adapter);
        } else {
            video_adapter.notifyDataSetChanged();
        }

    }

    /**
     * 解析数据
     *
     * @param result
     * @param typeid
     */
    private ArrayList<Video_Bean> toStr(String result, String typeid) {
        Map<String, ArrayList<Video_Bean>> map = new Gson().fromJson(result, new TypeToken<Map<String, ArrayList<Video_Bean>>>() {
        }.getType());
        ArrayList<Video_Bean> list = map.get(typeid);
        return list;
    }


    private void initView(View view) {
        xlv = (XListView) view.findViewById(R.id.video_xlv);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        index = 0;
        arrayList.clear();
        //请求数据
        getvideo(mParam1, mParam2, index);
        //上次刷新时间
        xlv.setRefreshTime(getTime());
        //关闭
        xlv.stopRefresh();

    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        index = index + 1;
        //请求数据
        getvideo(mParam1, mParam2, index);
        xlv.stopLoadMore();
    }

    /**
     * 计算时间
     *
     * @return
     */
    private String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }

    @Override
    public void onPause() {
        super.onPause();
        if (cancelable != null) {//取消请求
            cancelable.cancel();
        }
    }
}
